<template>
  <main class="container" v-if="isLogin">
    <main class="content">
      <!-- 商品模块 -->
      <div class="goods_list" v-if="list.length > 0">
        <van-swipe-cell v-for="item in list" :key="item.id" class="goods_item">
          <van-checkbox class="selected" v-model="item.checked"></van-checkbox>
          <div class="goods_box">
            <van-card
              class="goods_card"
              :num="item.count"
              :price="((item.goods_info.price / 100) * item.count).toFixed(2)"
              :desc="item.goods_info.brand"
              :title="item.goods_info.name"
              :thumb="item.goods_info.pic_url"
            >
              <template #tags>
                <van-tag plain type="primary">{{
                  item.goods_info.tags
                }}</van-tag>
              </template>
              <template #footer>
                <van-stepper v-model="item.count" />
              </template>
            </van-card>
          </div>

          <template #right>
            <van-button
              square
              class="delete-button"
              type="danger"
              @click="deleteGoods(item.id)"
              >删除</van-button
            >
          </template>
        </van-swipe-cell>
      </div>
      <div v-else>
        <van-empty description="当前购物车无商品">
          <van-button
            @click="router.replace('/home')"
            round
            type="primary"
            class="bottom-button"
            >去首页</van-button
          >
        </van-empty>
      </div>
    </main>

    <!-- 底部 提交订单 -->
    <van-submit-bar
      v-if="list.length > 0"
      class="submit"
      :price="countPrice"
      button-text="提交订单"
      @click="onSubmit"
    >
      <van-checkbox :checked="isAllChecked" @click="checkedAll"
        >全选</van-checkbox
      >
    </van-submit-bar>
  </main>
  <div v-else>
    <van-empty description="请先登录">
      <van-button
        @click="router.replace('/login')"
        round
        type="primary"
        class="bottom-button"
        >去登录</van-button
      >
    </van-empty>
  </div>
</template>

<script setup>
import { showConfirmDialog, showSuccessToast } from "vant";
import useCartInfo from "@/store/useCartInfo";
import { cartEdit, cartDelete } from "@/api/cart";
import { storeToRefs } from "pinia";
import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { getToken } from "@/utils/token";
// 创建路由实例
let router = useRouter();
// 购物车仓库实例
let cartStore = useCartInfo();
// 仓库解构出 响应式List
let { list } = storeToRefs(cartStore);

let isLogin = ref(!!getToken());

// 计算选中的商品总价值
let countPrice = computed(() => {
  let num = 0;
  // 过滤出选中的商品
  let arr = list.value.filter((item) => item.checked);
  // 遍历每个选中商品的 计算数量*单价
  arr.forEach((item) => {
    num = num + item.count * item.goods_info.price;
  });
  return num;
});
// 修改商品数量
let countChange = async (item) => {
  await cartEdit({ id: item.id, goods_id: item.goods_id, count: item.count });
};
// 计算是否有商品被选中
// 计算属性 也是ref对象
let isAllChecked = computed(() => {
  // 判断是否所有商品的checked为true
  return list.value.every((item) => item.checked === true);
});
// 全选和反选
let checkedAll = () => {
  // 当前全选则变为false 非全选 则改为true
  let bol = !isAllChecked.value;
  // 遍历list 让内部的checked的值 全部切换
  list.value.forEach((item) => {
    item.checked = bol;
  });
};
// 删除商品
let deleteGoods = (id) => {
  showConfirmDialog({
    title: "确认删除",
    message: "是否确认删除该商品",
  })
    .then(async (res) => {
      // 确实确定执行删除逻辑
      await cartDelete({ ids: [id] });
      console.log(id);
      // 重新获取 最新的购物车数据
      cartStore.getCartInfo();
      showSuccessToast("删除成功");
    })
    .catch(() => {
      showSuccessToast("未删除");
    });
};

// 提交订单
let onSubmit = () => {
  // 判断是否已选中了商品 checkedList是我已经选中的购物车数据
  let checkedList = list.value.filter((item) => item.checked);
  // 拿到选中的购物车数据id
  let ids = checkedList.map((item) => item.id);
  if (checkedList.length) {
    // 跳转至地址选择
    router.push(`/address-list?isCart=1&checkedGoods=${ids}`);
  } else {
    showSuccessToast("请先选择商品");
  }
};
</script>

<style scoped lang="scss">
.delete-button {
  height: 100%;
}

.container {
  .login_btn {
    width: 280px;
  }
  main.content {
    margin-bottom: var(--van-submit-bar-height);
    .goods_list {
      .goods_item {
        position: relative;
        .selected {
          position: absolute;
          z-index: 2;
          left: 8px;
          top: 58px;
        }
        .goods_box {
          background: #f7f8fa;
          margin-top: 10px;
          .goods_card {
            margin-left: 30px;
          }
        }
        .delete-button {
          width: 100%;
          height: 100%;
        }
      }
    }
    .is_null {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 55vh;
      text-align: center;
      p.cart_tip {
        font-size: 18px;
      }
      .to_btn {
        margin-top: 16px;
        width: 180px;
      }
    }
  }
  .submit {
    bottom: var(--van-submit-bar-height);
  }
}
</style>